package com.vr.xuecheng.content.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vr.xuecheng.content.mapper.CourseCategoryMapper;
import com.vr.xuecheng.content.model.entity.CourseCategory;
import com.vr.xuecheng.content.service.ICourseCategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author hsh
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements ICourseCategoryService {

    private final CourseCategoryMapper courseCategoryMapper;

    private void treeBuild(CourseCategory courseCategory, Tree<String> treeNode) {
        // 每个节点的相关属性
        treeNode.setId(courseCategory.getId())
                .setName(courseCategory.getName())
                .setParentId(courseCategory.getParentid())
                .setWeight(courseCategory.getOrderby());
        // 其他属性
        treeNode.putExtra("label", courseCategory.getLabel());
        treeNode.putExtra("isShow", courseCategory.getIsShow());
        treeNode.putExtra("isLeaf", courseCategory.getIsLeaf());
    }

    @Override
    public List<Tree<String>> getCourseCategoryTreeNodes() {
        // 1、查询出所有分类并构建数据
        List<CourseCategory> courseCategoryList = courseCategoryMapper.selectList(null);

        if (courseCategoryList==null || courseCategoryList.isEmpty()) {
            return Collections.emptyList();
        }
        // 2、配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 显示数据的别名
        treeNodeConfig.setIdKey("id")
                .setWeightKey("orderby")
                .setDeep(3)
                .setParentIdKey("parentid")
                .setNameKey("name")
                .setChildrenKey("childrenTreeNodes");

        return TreeUtil.build(courseCategoryList, "1", treeNodeConfig, this::treeBuild);
    }
}
